package com.credithc.signature.job.service;

import com.credithc.signature.common.constant.FddConstant;
import com.credithc.signature.common.mapper.ProductSignMapper;
import com.credithc.signature.common.po.ProductSign;
import com.credithc.signature.common.po.SignatureLog;
import com.credithc.signature.common.ro.core.CoreRequet;
import com.credithc.signature.common.service.SignatureLogService;
import com.credithc.signature.common.utils.AmazonUtil3;
import com.credithc.signature.common.utils.HttpUploadUtil;
import com.credithc.signature.job.ro.JobRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：上传pdf服务<br/>
 * 作者：sunyang
 * 创建：2019/6/4 16:39
 * 版本：v1.0.0<br/>
 */
@Slf4j
@Service
public class UploadPDFService {

    @Value("${signature.fileServer.http.url}")
    private String url;

    @Value("${signature.YNXJD.channelNo:1015}")
    private String YNXJDChannelNo;

    @Value("${signature.YNXJDBY.channelNo:1017}")
    private String YNXJDBYChannelNo;

    @Value("${signature.aliyun.endpoint:oss-ap-southeast-5.aliyuncs.com}")
    private String aliyunEndpoint;

    @Value("${signature.aliyun.oosKey:LTAIj7AQc5BZGwFN}")
    private String oosKey;

    @Value("${signature.aliyun.oosSecret:WU471BjsLXFhSmhSmTlJb5MZzCAZhW}")
    private String oosSecret;

    @Value("${signature.aliyun.bucket:contractoss}")
    private String bucket;

    @Autowired
    private SignatureLogService signatureLogService;

    @Autowired
    private ProductSignMapper productSignMapper;

    /**
     * 上传PDF文件到服务器
     *
     * @param pdfPath
     * @return
     */
    public String uploadPDF(String pdfPath, JobRequest coreRequet) throws Exception {
        File file = new File(pdfPath);
        if (!file.exists()) {
            log.error("－消息－:requestSn={},文件不存在,上传失败", coreRequet.getRequestSn(), pdfPath);
            throw new Exception("文件:{" + pdfPath + "}不存在");
        }
        String fileSystemName = null;
        try {
            // 上传到文件系统
            String name = file.getName();
            String uploadFilePath = null;
            // 判断签章供应商
            Example pse = new Example(ProductSign.class);
            Example.Criteria psec = pse.createCriteria();
            psec.andEqualTo("productCode", coreRequet.getChannelNo());
            List<ProductSign> productSigns = productSignMapper.selectByExample(pse);
            if (productSigns != null) {
                Map<String, Integer> map = new HashMap();
                for (ProductSign p : productSigns) {
                    map.put(p.getMethodName(), p.getPercentage());
                }
                // 上传到S3文件系统
                Integer fddSignature = map.get(FddConstant.FDDSIGNATURE);
                if (fddSignature != null && fddSignature == 100) {
                    fileSystemName = "S3文件服务器";
                    File file1 = new File(pdfPath);
                    String contractId = getFileId(pdfPath);
                    AmazonUtil3.uploadToS3(file1, contractId);
                    uploadFilePath = contractId;
                } else {
                    // 上传到FASTDFS文件系统
                    fileSystemName = "FASTDFS文件服务器";
                    uploadFilePath = HttpUploadUtil.upload(pdfPath, name, coreRequet.getRequestSn(), url);
                }
            } else {
                // 上传到FASTDFS文件系统
                fileSystemName = "FASTDFS文件服务器";
                uploadFilePath = HttpUploadUtil.upload(pdfPath, name, coreRequet.getRequestSn(), url);
            }
            // 更新数据库
            updateCreatePDFStatus(true, coreRequet.getRequestSn(), uploadFilePath);
            // 为了节约磁盘空间，上传成功之后删除文件
            removeUploadFile(pdfPath);
            return uploadFilePath;
        } catch (Exception e) {
            log.error("－消息－:requestSn={},上传到文件系统失败,文件系统为:{},失败原因:{}", coreRequet.getRequestSn(), fileSystemName, e.getMessage());
            updateCreatePDFStatus(false, coreRequet.getRequestSn(), "");
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取文件ID
     *
     * @param filePath
     * @return
     */
    public static String getFileId(String filePath) {
        String[] snapPdf_s = filePath.split("snapPdf_");
        String snapPdf_ = snapPdf_s[1];
        String s = snapPdf_.split(".pdf")[0];
        return s;
    }

    /**
     * 删除上传成功的文件
     *
     * @param filePath
     */
    public static void removeUploadFile(String filePath) {
        //1.删除签章之前的合同文件
        String newPath = filePath.replace("sign-pdf", "nosign-pdf");
        try {
            File file = new File(newPath);
            if (file.exists()) {
                file.delete();
                log.debug("删除未签章临时合同文件成功......合同路径：{}", newPath);
            }
        } catch (Exception e) {
            log.error("删除未签章临时合同文件失败......合同路径：{}", newPath, e);
        }
        //2.删除签完章的合同文件
        try {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
                log.debug("删除已签章合同文件成功......合同路径：{}", filePath);
            }
        } catch (Exception e) {
            log.error("删除已签章合同文件失败......合同路径：{}", filePath, e);
        }
    }

    public void removeUnusedFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
                log.debug("删除不使用的合同文件成功......合同路径：{}", filePath);
            }
        } catch (Exception e) {
            log.error("删除不使用的合同文件成功......合同路径：{}", filePath, e);
        }
    }

    //*-*!
    private void updateCreatePDFStatus(boolean isSuccess, String requestSn, String uploadFilePath) {
        SignatureLog signatureLog = new SignatureLog();
        signatureLog.setRequestSn(requestSn);
        signatureLog.setUploadPdfStatus(isSuccess ? 1 : 2);
        signatureLog.setContractUri(uploadFilePath);
        signatureLogService.updateByReqSNSelective(signatureLog);
    }
}
